<template>
  <div>
    <div class="mb-8">
      <div class="flex justify-between items-center">
        <div>
          <h1 class="text-3xl font-bold text-gray-800 mb-2">个人资料</h1>
          <p class="text-gray-600">管理您的个人信息和账户设置</p>
        </div>
        <div class="flex space-x-3">
          <button @click="handleSave" :disabled="loading" 
                  class="bg-blue-600 hover:bg-blue-700 disabled:bg-gray-400 text-white px-6 py-2 rounded-lg font-medium shadow-lg hover:shadow-xl transition">
            <i class="fas fa-save mr-2"></i>保存修改
          </button>
          <button @click="handleCancel" 
                  class="bg-white hover:bg-gray-50 text-gray-700 px-6 py-2 rounded-lg font-medium shadow-lg border border-gray-200 transition">
            <i class="fas fa-times mr-2"></i>取消
          </button>
        </div>
      </div>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
      <!-- 左侧：头像和基本信息 -->
      <div class="lg:col-span-1">
        <div class="bg-white p-6 rounded-2xl shadow-lg border border-gray-100">
          <div class="text-center">
            <div class="relative inline-block">
              <img :src="defaultAvatar" 
                   class="w-32 h-32 rounded-full border-4 border-gray-200 object-cover mx-auto mb-4"/>
              <button @click="handleAvatarChange" 
                      class="absolute bottom-2 right-2 w-8 h-8 bg-blue-600 text-white rounded-full flex items-center justify-center hover:bg-blue-700 transition">
                <i class="fas fa-camera text-sm"></i>
              </button>
            </div>
            <h3 class="text-xl font-semibold text-gray-800 mb-2">{{ formData.name || '管理员' }}</h3>
            <p class="text-gray-500 mb-4">{{ formData.roleName || '系统管理员' }}</p>
            <div class="text-sm text-gray-600 space-y-1">
              <p v-if="formData.email"><i class="fas fa-envelope mr-2"></i>{{ formData.email }}</p>
              <p v-if="formData.phone"><i class="fas fa-phone mr-2"></i>{{ formData.phone }}</p>
              <p v-if="formData.createdAt"><i class="fas fa-calendar mr-2"></i>注册时间：{{ formatDate(formData.createdAt) }}</p>
            </div>
          </div>
        </div>

      </div>

      <!-- 右侧：详细信息编辑 -->
      <div class="lg:col-span-2">
        <div class="bg-white p-6 rounded-2xl shadow-lg border border-gray-100">
          <h4 class="text-lg font-semibold text-gray-800 mb-6">
            <i class="fas fa-user-edit text-blue-500 mr-2"></i>基本信息
          </h4>
          
          <form @submit.prevent="handleSave" class="space-y-6">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">姓名</label>
                <input v-model="formData.name" 
                       type="text" 
                       class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition"
                       placeholder="管理员"/>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">用户名</label>
                <input v-model="formData.username" 
                       type="text" 
                       disabled
                       class="w-full px-4 py-3 border border-gray-300 rounded-lg bg-gray-100 text-gray-500"
                       placeholder="用户名不可修改"/>
              </div>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">邮箱</label>
                <input v-model="formData.email" 
                       type="email" 
                       class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition"
                       placeholder="请输入邮箱地址"/>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">手机号</label>
                <input v-model="formData.phone" 
                       type="tel" 
                       class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition"
                       placeholder="请输入手机号"/>
              </div>
            </div>


            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">个人简介</label>
              <textarea v-model="formData.bio" 
                        rows="4" 
                        class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition resize-none"
                        placeholder="请输入个人简介"></textarea>
            </div>
          </form>
        </div>

        <!-- 系统信息 -->
        <div class="bg-white p-6 rounded-2xl shadow-lg border border-gray-100 mt-6">
          <h4 class="text-lg font-semibold text-gray-800 mb-6">
            <i class="fas fa-info-circle text-blue-500 mr-2"></i>系统信息
          </h4>
          
          <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">用户ID</label>
              <input :value="formData.id" 
                     type="text" 
                     disabled
                     class="w-full px-4 py-3 border border-gray-300 rounded-lg bg-gray-100 text-gray-500"/>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">角色</label>
              <input :value="formData.roleName" 
                     type="text" 
                     disabled
                     class="w-full px-4 py-3 border border-gray-300 rounded-lg bg-gray-100 text-gray-500"/>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">最后登录时间</label>
              <input :value="formatDate(formData.lastLoginAt)" 
                     type="text" 
                     disabled
                     class="w-full px-4 py-3 border border-gray-300 rounded-lg bg-gray-100 text-gray-500"/>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">账户状态</label>
              <div class="flex items-center px-4 py-3 border border-gray-300 rounded-lg bg-gray-100">
                <span class="text-green-600 font-medium">正常</span>
                <i class="fas fa-check-circle text-green-500 ml-2"></i>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { authAPI } from '@/api/modules'
import { ElMessage } from 'element-plus'

const router = useRouter()
const authStore = useAuthStore()
const loading = ref(false)

// 默认头像
const defaultAvatar = 'https://ui-avatars.com/api/?name=Admin&background=3b82f6&color=ffffff&size=150&bold=true'

// 表单数据
const formData = reactive({
  id: null,
  username: '',
  name: '',
  email: '',
  phone: '',
  bio: '',
  avatar: '',
  roleName: '',
  createdAt: null,
  lastLoginAt: null
})


/**
 * 格式化日期
 */
const formatDate = (dateString) => {
  if (!dateString) return '未知'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

/**
 * 加载用户信息
 */
const loadUserInfo = async () => {
  try {
    const response = await authAPI.getUserInfo()
    if (response.code === 0) {
      const userInfo = response.data
      Object.assign(formData, {
        id: userInfo.id,
        username: userInfo.username,
        name: userInfo.name || userInfo.realName,
        email: userInfo.email,
        phone: userInfo.phone,
        bio: userInfo.bio,
        avatar: userInfo.avatar,
        roleName: userInfo.roleName || '系统管理员',
        createdAt: userInfo.createdAt,
        lastLoginAt: userInfo.lastLoginAt
      })
    }
  } catch (error) {
    console.error('加载用户信息失败:', error)
    // 使用默认数据
    Object.assign(formData, {
      id: 1,
      username: 'admin',
      name: '管理员',
      email: 'admin@example.com',
      phone: '138****8888',
      bio: '系统管理员，负责系统维护和管理工作',
      avatar: '',
      roleName: '系统管理员',
      createdAt: '2024-01-01T00:00:00',
      lastLoginAt: new Date().toISOString()
    })
  }
}

/**
 * 保存个人信息
 */
const handleSave = async () => {
  loading.value = true
  try {
    const response = await authAPI.updateProfile({
      name: formData.name,
      email: formData.email,
      phone: formData.phone,
      bio: formData.bio
    })
    
    if (response.code === 0) {
      ElMessage.success('个人信息保存成功')
      // 更新store中的用户信息
      authStore.updateUserInfo(formData)
    } else {
      ElMessage.error(response.message || '保存失败')
    }
  } catch (error) {
    console.error('保存个人信息失败:', error)
    ElMessage.error('保存失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

/**
 * 取消修改
 */
const handleCancel = () => {
  ElMessage.info('已取消修改')
  router.push('/admin/dashboard')
}

/**
 * 修改头像
 */
const handleAvatarChange = () => {
  ElMessage.info('头像修改功能开发中')
}


onMounted(() => {
  loadUserInfo()
})
</script>

<style scoped>
/* 自定义样式 */
.transition {
  transition: all 0.3s ease;
}

/* 头像上传按钮悬停效果 */
.relative:hover .absolute {
  transform: scale(1.1);
}

/* 表单输入框聚焦效果 */
input:focus, textarea:focus {
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

/* 按钮悬停效果 */
button:hover:not(:disabled) {
  transform: translateY(-1px);
}

/* 模态框动画 */
.fixed {
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
</style>
